package com.common.zrd.mapper.mymapper;

import cn.hutool.core.util.StrUtil;
import com.common.zrd.mapper.OrderAnnotation;
import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: zrd
 * @Date: 2020/4/15 14:39
 * @Description:
 */
public class QueryProvider extends MapperTemplate {
    public QueryProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
        super(mapperClass, mapperHelper);
    }

    /**
     * 驼峰法转下划线
     *
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camel2Underline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase()
                .concat(line.substring(1));
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }

    public String seletCommonList(MappedStatement ms) {
        final Class<?> entityClass = getEntityClass(ms);
        //修改返回值类型为实体类型
        setResultType(ms, entityClass);
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.selectAllColumns(entityClass));
        sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));

        sql.append(SqlHelper.whereAllIfColumns(entityClass, true));
        Field[] fields = entityClass.getDeclaredFields();
        sql.append(" order by");
        for (Field field : fields) {
            OrderAnnotation translateAnnotation = field.getAnnotation(OrderAnnotation.class);
            //获取属性上的@OrderAnnotation排序

            if (translateAnnotation != null) {
                sql.append(" " + camel2Underline(field.getName()) + " " + translateAnnotation.orderType().getKey() +
                        ",");
            }
        }
        String rs = sql.toString();
        //如果末尾以 ，结束  截取掉
        if (rs.endsWith(",")) {
            rs = rs.substring(0, rs.length() - 1);
        }
        //如果 排序的注解一个都没有  删掉拼接的order by
        if (rs.endsWith("order by")) {
            // rs= rs.substring(0, rs.indexOf("order by"));
            rs = StrUtil.subBefore(rs, "order by", true);
        }
        return rs;

    }

}
